package com.david.viewtest.view

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.widget.FrameLayout
import android.widget.OverScroller


class CustomFrameLayout(context: Context?, attrs: AttributeSet) : FrameLayout(context!!, attrs) {
    //private val gestureDetector: GestureDetector
    private var startX = 0f
    private var startY = 0f
    private var lastX = 0f
    private var lastY = 0f
    init {
        //gestureDetector = GestureDetector(context, MyGestureListener())
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return true
    }

    var time = 0L


    var deltaX = 0f
    var deltaY = 0f
    var duration = 0L

    private var mLastX = 0f
    private var mLastY = 0f

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mLastX = x
                mLastY = y

                time = System.currentTimeMillis()

            }

            MotionEvent.ACTION_MOVE -> {
                deltaX = x - mLastX
                deltaY = y - mLastY
                scrollBy((-deltaX).toInt(), (-deltaY).toInt())
                mLastX = x
                mLastY = y
                duration = System.currentTimeMillis() - time
                time = System.currentTimeMillis()

            }

            MotionEvent.ACTION_UP -> {
                startFling()
            }
        }
        return true
    }

    private val flingTask = Runnable {
        deltaX *= 0.9f
        deltaY *= 0.9f
        scrollBy((-deltaX).toInt(), (-deltaY).toInt())

        if (deltaX > 0.0001f || deltaY > 0.0001f) {
            startFling()
        }
    }
    private fun startFling() {
        postDelayed(flingTask, duration)
    }
}



